package me.liuhui.mall.manager.service.security;

import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import me.liuhui.mall.common.base.vo.ResultVO;
import me.liuhui.mall.manager.service.AdminTokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@AllArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private AdminTokenService adminTokenManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        CurrentAdmin admin = (CurrentAdmin) authentication.getPrincipal();
        String token = adminTokenManager.createToken(admin);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(JSONUtil.toJsonStr(ResultVO.success(token)));
    }
}
